<script setup lang="ts">
defineOptions({
  name: "checkListItem"
});

import { ref, reactive, computed, watch, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import sop from "./sop.vue";
import upload from "./upload.vue";
import dayjs from "dayjs";
import { cloneDeep } from "@pureadmin/utils";

interface Props {
  data: Record<string, any>;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  data: () => ({ data: null, title: "" }),
  disabled: false
});

const isNotEdit = ref<boolean>(true);
const isShowEditBtn = ref<boolean>(false);
const sopRef = ref<any>(null);
const uploadRef = ref<InstanceType<typeof upload> | null>(null);
const uploadData = ref<{ imgList: Array<any>; fileList: Array<any>; executeRemark: string }>({
  imgList: [],
  fileList: [],
  executeRemark: ""
});

const extraFormRef = ref<FormInstance>(null);
interface FormType {
  operator: string;
  confirmor: string;
  startTime: string;
  endTime: string;
}
const extraForm = ref<FormType>({
  operator: "",
  confirmor: "",
  startTime: "",
  endTime: ""
});
const extraFormRules = reactive<FormRules<FormType>>({
  operator: [{ required: true, message: "请输入值班工程师", trigger: ["blur"] }],
  confirmor: [{ required: true, message: "请输入厂商操作员", trigger: ["blur"] }],
  startTime: [{ required: true, message: "请选择开始日期", trigger: ["blur"] }],
  endTime: [{ required: true, message: "请选择结束日期", trigger: ["blur"] }]
});

const realDisabled = computed(() => props.disabled || isNotEdit.value);

const endDisabledDateFn = (d: Date) => {
  const currentTimeStamp = Date.now();
  const timeStamp = new Date(d).getTime();
  if (timeStamp < currentTimeStamp - 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (timeStamp > currentTimeStamp + 6 * 30 * 24 * 60 * 60 * 1000) return true;
  if (extraForm.value.startTime && timeStamp < dayjs(extraForm.value.startTime).valueOf()) return true;
  return false;
};

const validate = async () => {
  await extraFormRef.value.validate();
  for (const item of Array.from(sopRef.value)) {
    await item?.validate();
  }
  await uploadRef.value.validate();
};

const getSopParams = () => {
  if (!sopRef.value) return [];
  let list = [];
  for (const item of Array.from(sopRef.value)) {
    const p = item?.list;
    list.push(...p);
  }
  return list;
};

const getParams = () => {
  const { id = "" } = props.data;
  const { operator = "", confirmor = "", startTime = "", endTime = "" } = extraForm.value;
  let taskChecklistResult = cloneDeep(getSopParams());
  taskChecklistResult = taskChecklistResult.map(item => {
    delete item.status;
    return item;
  });
  let fileIdList = [];
  let imgIdList = [];
  const { imgList = [], fileList = [], executeRemark = "" } = uploadData.value;
  fileList?.length && (fileIdList = fileList.map(item => item.id));
  imgList?.length && (imgIdList = imgList.map(item => item.id));
  const subTaskDTO = { id, taskChecklistResult, imgIdList, fileIdList, executeRemark };
  return { subTaskDTO, operator, confirmor, startTime, endTime };
};

const init = () => {
  const { operator = "", confirmor = "", imgList = [], fileList = [], executeRemark = "", startTime = "", endTime = "" } = props.data;
  extraForm.value.operator = operator;
  extraForm.value.confirmor = confirmor;
  extraForm.value.startTime = startTime;
  extraForm.value.endTime = endTime;
  uploadData.value.imgList = imgList;
  uploadData.value.fileList = fileList;
  uploadData.value.executeRemark = executeRemark;
  uploadRef.value.init();
};

watch(
  () => props.data,
  val => {
    if (val) {
      const { executor = "", subTaskTypeDesc = "", isLastExecutor = false, firstEmptyTitle = "", isLast = false } = val;
      if (props.disabled) {
        isShowEditBtn.value = false;
        isNotEdit.value = true;
      } else if (!!executor) {
        if (isLastExecutor) {
          const userInfo = localStorage.getItem("userInfo");
          const { userId = null } = JSON.parse(userInfo);
          if (userId === executor) {
            isShowEditBtn.value = true;
            isNotEdit.value = true;
          } else {
            isShowEditBtn.value = false;
            isNotEdit.value = true;
          }
          if (isLast) {
            isShowEditBtn.value = false;
          }
        } else {
          isShowEditBtn.value = false;
          isNotEdit.value = true;
        }
      } else {
        if (subTaskTypeDesc === firstEmptyTitle) {
          // 当前需要填入的项
          isShowEditBtn.value = false;
          isNotEdit.value = false;
        } else {
          // 在当前需要填入项后面的项
          isShowEditBtn.value = false;
          // 目前暂时放开
          isNotEdit.value = false;
        }
      }
    }
  },
  {
    immediate: true,
    once: true
  }
);

onMounted(() => {
  init();
});

defineExpose({
  init,
  validate,
  getParams
});
</script>

<template>
  <div>
    <div class="collapse-content-form">
      <px-form
        ref="extraFormRef"
        inline
        label-width="120px"
        :model="extraForm"
        :rules="extraFormRules"
        :disabled="realDisabled"
        scroll-to-error
        :scroll-into-view-options="{ behavior: 'smooth' }"
      >
        <px-row :gutter="32">
          <!-- <px-col :span="8">
            <px-form-item label="值班工程师" prop="operator">
              <px-input v-model.trim="extraForm.operator" clearable placeholder="请输入值班工程师" />
            </px-form-item>
          </px-col>
          <px-col :span="8">
            <px-form-item label="厂商操作员" prop="confirmor">
              <px-input v-model.trim="extraForm.confirmor" clearable placeholder="请输入厂商操作员" />
            </px-form-item>
          </px-col> -->
          <px-col :span="8">
            <px-form-item label="开始日期" prop="startTime">
              <px-date-picker
                v-model="extraForm.startTime"
                clearable
                type="datetime"
                :editable="false"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 1, 1, 0, 0, 0)"
                placeholder="请选择开始日期"
              />
            </px-form-item>
          </px-col>
          <px-col :span="8">
            <px-form-item label="结束日期" prop="endTime">
              <px-date-picker
                v-model="extraForm.endTime"
                clearable
                type="datetime"
                :editable="false"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                :disabled-date="endDisabledDateFn"
                placeholder="请选择结束日期"
              />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
    </div>
    <div class="collapse-content-sop">
      <div v-for="item in data.data" :key="item.title" class="collapse-content-sop-item">
        <div class="collapse-content-sop-title">{{ item?.title }}</div>
        <sop ref="sopRef" :disabled="realDisabled" :data="item?.data" :title="item?.title" />
      </div>
    </div>
    <upload ref="uploadRef" v-model="uploadData" :disabled="realDisabled" />
    <!-- <div class="btns">
      <px-button v-if="isShowEditBtn" type="primary" plain @click="editHandler">再次编辑</px-button>
      <px-button v-if="!realDisabled" type="primary" @click="submitHandler">提交</px-button>
      <px-button v-if="!realDisabled" type="primary" plain @click="saveHandler">保存为草稿</px-button>
    </div> -->
  </div>
</template>

<style lang="scss" scoped>
.collapse-content-sop {
  .collapse-content-sop-item {
    &:not(:first-of-type) {
      margin-top: 16px;
    }

    .collapse-content-sop-title {
      margin-bottom: 10px;
      font-size: 15px;
      font-weight: 600;
      color: #333;
    }
  }
}

.btns {
  display: flex;
  align-items: center;
}
</style>
